package com.example.springbootdemo.bean.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.springbootdemo.bean.kernelApi.LoginData;
import com.example.springbootdemo.bean.kernelApi.Result;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class AnyConnectionManager {

    @Autowired
    HubConnectionManager hubConnectionManager;

    @Getter
    private HubConnection hubConnection;


    @PostConstruct
    public void initializeAnyConnection() {
        String wssUrl="https://orginone.cn/orginone/anydata/hub";
        hubConnection = HubConnectionBuilder.create(wssUrl).build();
        hubConnection.setKeepAliveInterval(3000);
        hubConnection.on("ReceiveMessage", (message) -> {
            System.out.println("Received message: " + message);
        }, String.class);

        hubConnection.onClosed((err) -> {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                log.error("InterruptedException while sleeping: " + e.getMessage());
                initializeAnyConnection();
            }
//            reconnect();
            hubConnection.start().blockingAwait();
        });
//        reconnect();
        hubConnection.start().blockingAwait();
    }
    private void reconnect() {
        log.info("Reconnecting to SignalR hub...");
        hubConnection.start().subscribe(
                () -> {
                    log.info("Reconnected to SignalR hub");
                },

                error -> log.error("Error while reconnecting: " + error.getMessage())
        );
    }

    public void  tokenAuthConnection() {
        hubConnection.invoke("TokenAuth", hubConnectionManager.getHubConnectionToken()).blockingAwait();
    }
}
